<template>
  <view class="profile-page">
    <!-- 1. 顶部导航栏（符合手册2.7导航规范） -->
    <view class="nav-bar">
      <navigator 
        class="nav-back" 
        url="/pages/mine/mine" 
        open-type="navigateBack"
      >
        ←
      </navigator>
      <view class="nav-title">个人信息</view>
      <view class="nav-empty"></view> <!-- 占位，保持标题居中 -->
    </view>

    <!-- 2. 头像与基础信息区（手册2.5.1图片适配 + 2.2.1 flex布局） -->
    <view class="avatar-area">
      <view class="avatar-wrap" @click="chooseAvatar">
        <image 
          class="avatar" 
          :src="userInfo.avatar || defaultAvatar" 
          mode="aspectFill"
          @error="handleImgError"
        ></image>
        <view class="avatar-mask">
          <text class="mask-text">点击更换头像</text>
        </view>
      </view>
      <view class="basic-info">
        <text class="nickname">{{ userInfo.nickname || '未设置昵称' }}</text>
        <text class="user-id">用户ID: {{ userInfo.id || '未知' }}</text>
      </view>
    </view>

    <!-- 3. 详细信息列表（手册1.5循环渲染 + 2.6事件处理） -->
    <view class="info-list">
      <view class="info-item" v-for="(item, idx) in infoList" :key="idx">
        <view class="item-label">{{ item.label }}</view>
        <view class="item-content">
          <text class="content-text">{{ item.value || '未填写' }}</text>
          <!-- 修复：事件绑定符合手册2.6规范，避免原生事件异常 -->
          <button class="edit-btn" @click="handleEdit(item.key, item.label)">
            ✏️
          </button>
        </view>
      </view>
    </view>

    <!-- 4. 底部操作区 -->
    <view class="action-area">
      <button 
        class="btn logout-btn" 
        @click="handleLogout"
        hover-class="logout-btn--active"
      >
        退出登录
      </button>
    </view>

    <!-- 安全区域适配（手册6.3多端适配） -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script>
export default {
  name: "Profile", // 手册1.6组件名语义化
  data() {
    return {
      defaultAvatar: '/static/img/default-avatar.png',
      userInfo: {
        id: "",
        nickname: "",
        avatar: "",
        mobile: "",
        email: ""
      },
      infoList: [
        { label: "昵称", key: "nickname", value: "" },
        { label: "手机号", key: "mobile", value: "" },
        { label: "邮箱", key: "email", value: "" }
      ],
      // 新增：编辑用临时变量（手册1.5数据初始化规范）
      editValue: ""
    };
  },
  onLoad() {
    this.initUserInfo(); // 手册4.2页面加载初始化
  },
  methods: {
    async initUserInfo() {
      // 优先从后端拉取新鲜信息
      try {
        const { myRequest } = require('@/util/request.js');
        const data = await myRequest({ url: '/api/user/info', method: 'GET' });
        const merged = { ...this.userInfo, ...data };
        this.userInfo = merged;
        this.infoList = this.infoList.map(item => ({
          ...item,
          value: merged[item.key]
        }));
        uni.setStorageSync('userInfo', merged);
      } catch (e) {
        // 回退到本地缓存
        const user = uni.getStorageSync('userInfo');
        if (typeof user === 'object' && user !== null) {
          this.userInfo = { ...this.userInfo, ...user };
          this.infoList = this.infoList.map(item => ({
            ...item,
            value: this.userInfo[item.key]
          }));
        }
      }
    },

    chooseAvatar() {
      uni.chooseImage({ // 手册8.1图片上传API
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          const tempAvatarUrl = res.tempFilePaths[0];
          this.previewAvatar(tempAvatarUrl);
          this.userInfo.avatar = tempAvatarUrl;
          uni.setStorageSync("userInfo", this.userInfo); // 手册5.1缓存写入
          uni.showToast({ title: "头像更新成功", icon: "success" }); // 手册7.2交互提示
        }
      });
    },

    previewAvatar(url) {
      uni.previewImage({ // 手册8.2图片预览API
        current: url,
        urls: [url],
        loop: true
      });
    },

    handleImgError(e) {
      if (e.target.src !== this.defaultAvatar) {
        e.target.src = this.defaultAvatar; // 手册2.5.1图片容错
      }
    },

    // 编辑个人信息
    async handleEdit(key, label) {
      const currentValue = this.userInfo[key] || "";
      
      // 手机号不允许修改
      if (key === 'mobile') {
        uni.showToast({
          title: "手机号不支持修改",
          icon: "none"
        });
        return;
      }
      
      // 使用uni.prompt进行输入
      uni.showModal({
        title: `编辑${label}`,
        placeholderText: `请输入${label}`,
        editable: true,
        content: currentValue,
        success: async (res) => {
          if (res.confirm) {
            const newValue = res.content ? res.content.trim() : "";
            
            if (!newValue) {
              uni.showToast({
                title: `${label}不能为空`,
                icon: "none"
              });
              return;
            }
            
            try {
              // 调用后端API更新用户信息
              const { myRequest } = require('@/util/request.js');
              await myRequest({
                url: '/api/user/info',
                method: 'PUT',
                data: {
                  username: key === 'nickname' ? newValue : this.userInfo.nickname,
                  email: key === 'email' ? newValue : this.userInfo.email
                }
              });
              
              // 更新本地数据
              this.userInfo[key] = newValue;
              this.infoList = this.infoList.map(item => 
                item.key === key ? { ...item, value: newValue } : item
              );
              
              // 保存到缓存
              uni.setStorageSync("userInfo", this.userInfo);
              
              uni.showToast({
                title: "修改成功",
                icon: "success"
              });
            } catch (err) {
              uni.showToast({
                title: err.message || "修改失败",
                icon: "none"
              });
            }
          }
        }
      });
    },

    handleLogout() {
      uni.showModal({ // 手册2.4.1按钮交互规范
        title: "提示",
        content: "确定要退出登录吗？",
        confirmText: "退出",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            try {
              uni.removeStorageSync("userInfo"); // 手册5.3缓存删除
              uni.navigateTo({ url: "/pages/mine/mine" }); // 手册2.7导航跳转
              uni.showToast({ title: "退出成功", icon: "success" });
            } catch (err) {
              console.error("退出失败:", err);
              uni.showToast({ title: "退出失败，请重试", icon: "none" });
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
/* 复用原样式，符合手册1.7 SCSS变量规范 */
$primary-color: #3E88F0;
$secondary-color: #4CD964;
$gray-light: #F5F7FA;
$gray-mid: #999999;
$gray-dark: #333333;
$gap-size: 20rpx;
$btn-radius: 60rpx;
$border-width: 4rpx;
$safe-area: env(safe-area-inset-bottom, 0px);

page {
  background-color: $gray-light;
  min-height: 100vh;
  box-sizing: border-box;
}

.profile-page {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding-bottom: $safe-area;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: $gap-size * 1.5 $gap-size * 2;
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.nav-back {
  font-size: 36rpx;
  color: $gray-dark;
  width: 60rpx;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: $gray-dark;
  flex: 1;
  text-align: center;
}

.nav-empty {
  width: 60rpx;
}

.avatar-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: $gap-size * 3;
  background-color: #FFFFFF;
  margin: $gap-size;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.avatar-wrap {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: $gap-size * 2;
  border: 6rpx solid $primary-color;
  box-shadow: 0 4rpx 16rpx rgba(62, 136, 240, 0.2);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-mask {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 60rpx;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
}

.mask-text {
  font-size: 22rpx;
  color: #FFFFFF;
}

.basic-info {
  text-align: center;
}

.nickname {
  font-size: 34rpx;
  font-weight: 600;
  color: $gray-dark;
  margin-bottom: 8rpx;
  display: block;
}

.user-id {
  font-size: 24rpx;
  color: $gray-mid;
}

.info-list {
  background-color: #FFFFFF;
  margin: $gap-size;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $gap-size * 2;
  border-bottom: 2rpx solid $gray-light;
  &:last-child {
    border-bottom: none;
  }
}

.item-label {
  font-size: 28rpx;
  color: $gray-dark;
  width: 140rpx;
}

.item-content {
  display: flex;
  align-items: center;
  flex: 1;
  justify-content: space-between;
  padding-left: $gap-size;
}

.content-text {
  font-size: 28rpx;
  color: $gray-mid;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.edit-btn {
  background: transparent;
  border: none;
  font-size: 30rpx;
  color: $primary-color;
  padding: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-area {
  display: flex;
  justify-content: center;
  padding: $gap-size * 2;
  margin-top: auto;
}

.btn {
  padding: 22rpx 0;
  border-radius: $btn-radius;
  font-size: 28rpx;
  text-align: center;
  width: 300rpx;
  box-sizing: border-box;
  transition: all 0.2s ease;
}

.logout-btn {
  background-color: #FFFFFF;
  color: #FF4D4F;
  border: $border-width solid #FF4D4F;
  &:hover, &:active {
    background-color: rgba(255, 77, 79, 0.05);
  }
}

.safe-area-bottom {
  height: $safe-area;
}
</style>